package utils

import (
	"context"
	"fmt"
	"github.com/bingbaba/harbor-go"
	"github.com/bingbaba/harbor-go/models"
	"strings"
	"time"
)

type Client struct {
	Session *harbor.Client
}

var Login Client

func init() {
	c, err := harbor.NewClient(nil, host, username, password, true)
	if err != nil {
		panic(err)
	}
	Login = Client{
		Session: c,
	}
}

func Run() []string {
	id := Login.ListProject(projectName)
	repos := Login.ListRepo(id)
	return repos
}

// return mkcp project id
func (c Client) ListProject(projectName string) int64 {
	var id int64
	ps, err := c.Session.ListProjects(context.Background(), nil)
	if err != nil {
		panic(err)
	}

	for _, p := range ps {
		if p.Name == projectName {
			id = p.ProjectID
		}
	}

	return id
}

func (c Client) ListRepo(id int64) []string {
	var RepoList []string
	_, r, err := c.Session.ListRepos(context.Background(), id, nil)
	if err != nil {
		panic(err)
	}
	for _, repo := range r {
		RepoList = append(RepoList, repo.Name)
	}
	return RepoList
}

func (c Client) GetImages(projectName, repoName string) []*models.TagDetail {
	ms, err := c.Session.ListRepoTags(context.Background(), projectName, repoName)
	if err != nil {
		fmt.Println(err)
	}
	return ms
}

func (c Client) DeleteImages(projectName, repoName, tagName string) {
	b, err := c.Session.DeleteRepoTag(context.Background(), projectName, repoName, tagName)
	if err != nil {
		fmt.Println(err)
	}
	if b {
		fmt.Printf("Project: %s repo: %s tag: %s delete sucessed!\n", projectName, repoName, tagName)
	}
}

func DeleteOldImages(item string, days int) {
	nowTime := time.Now()
	id := Login.ListProject(item)
	repos := Login.ListRepo(id)
	for _, i := range repos {
		repoName := strings.Replace(i, fmt.Sprintf("%s/", item), "", -1)
		for _, i := range Login.GetImages(item, repoName) {
			dates := int(nowTime.Sub(i.Created).Hours()) / 24
			if i.Name != "latest" && dates > days {
				Login.DeleteImages(item, repoName, i.Name)
			}
		}
	}
}
